//
//  ZYComposeTextView + EXtension.swift
//  weiboZY
//
//  Created by 赵勇 on 16/5/23.
//  Copyright © 2016年 赵勇. All rights reserved.
//

import UIKit

extension ZYComposeTextView {
    
    var emoticonText: String {
        
        // 获取表情对应的文本附件
        
        var result = ""
        
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) -> Void in
            
            if let attachment = infoDic["NSAttachment"] as? ZYEmoticonTextAttachment {
                // 信息文本附件 表qing
                
                let chs = attachment.emoticon?.chs
                result += chs!
                
            } else {
                // 信息是文本
                let textStr = self.self.attributedText.attributedSubstringFromRange(range).string
                result += textStr
                
            }
            
        }
        
        return result
        
    }
    
    
    
    
    func insertEmoticon (emotion:ZYEmoticon, font: UIFont) {
        
        if emotion.type == "0" {
            
            // 记录上一次的富文本
            var originalAttar = NSMutableAttributedString(attributedString: self.attributedText)
            
            // 1创建一个UIimage
            let image = UIImage(named: emotion.path!)
            
            // 2 根据UIImage对象创建一个NSTextAttachment
            let attachment = ZYEmoticonTextAttachment()
            
            attachment.emoticon = emotion
            attachment.image = image
            
            // 字体的高度
            let fontHeight = self.font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -3, width: fontHeight, height: fontHeight)
            
            // 3 根据NSTextAttachment创建一个NSAttributedString
            let attr = NSAttributedString(attachment: attachment)
            
            // 获取textview的选中范围
            var range = self.selectedRange
            
            // 替换选中的字符串
            originalAttar.replaceCharactersInRange(range, withAttributedString: attr)
            
            // 追加富文本
            //            originalAttar.appendAttributedString(attr)
            
            // 设置富文本字体大小
            originalAttar.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0,originalAttar.length))
            
            // 设置富文本
            self.attributedText = originalAttar
            // 每次点击按钮位置加 1
            range.location += 1
            // 设置选中范围为0
            range.length = 0
            // 选中范围
            self.selectedRange = range
            // 发送通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            // 自己使用代理调用代理方法 ? 判断可选方法是否实现
            self.delegate?.textViewDidChange?(self)
            
        } else {
    
            self.insertText((emotion.code! as NSString).emoji())
            
        }
        
        
        
    }
    
    
    
}




